<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="dictionaryDetails" highlight-current-row v-loading="listLoading"
				  @selection-change="selsChange"
				  @row-click="table = true"
				  style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="sn" label="类型编号" width="320" sortable>
			</el-table-column>
			<el-table-column prop="name" label="类型名称" width="320" sortable>
			</el-table-column>
			<el-table-column label="操作" width="350">
				<template scope="scope">
					<el-button size="small" @click="handleDictionaryDetail(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<el-drawer
				title="类型的详细数据"
				:visible.sync="table"
				direction="rtl"
				size="50%">
			<el-table :data="gridData">
				<el-table-column property="date" label="日期" width="150"></el-table-column>
				<el-table-column property="name" label="姓名" width="200"></el-table-column>
				<el-table-column property="address" label="地址"></el-table-column>
			</el-table>
		</el-drawer>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<!--:current-page="page" 处理当前页面已经跳转，但任然显示之前的页面状态的bug-->
			<el-pagination layout="prev, pager, next"
						   @current-change="handleCurrentChange"
						   :current-page="page"
						   :page-size="pageSize"
						   :total="total"
						   style="float:right;">
			</el-pagination>
		</el-col>

		<!--数据字典类型编辑和修改界面-->
		<!--:close-on-click-modal：是否可以通过点击 modal即模态框周围的模糊区域关闭 Dialog
			@close：模态框关闭事件的回调
			:visible.sync：是否显示 Dialog，支持 .sync 修饰符

			-->
		<el-dialog :title="title" :visible.sync="dictionaryDetailFormVisible" @close="closeDialog"  :close-on-click-modal="false">
			<el-form :model="dictionaryDetailForm" label-width="80px" :rules="dictionaryDetailFormRules" ref="dictionaryDetailForm">
				<el-form-item label="类型编号">
					<el-input v-model="dictionaryDetailForm.sn" auto-complete="off"></el-input>
				</el-form-item>
                <!--prop表单域 model 字段，在使用 validate、resetFields 方法的情况下，该属性是必填的,用于数据校验-->
                <el-form-item label="类型名称"  prop="name">
                    <el-input v-model="dictionaryDetailForm.name" auto-complete="off"></el-input>
                </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button  @click="closeForm('dictionaryDetailForm')">取消</el-button>
				<el-button type="primary" @click.native="dictionaryDetailSubmit" :loading="dictionaryDetailLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getDictionaryDetailListPage, removeDictionaryDetail, batchRemoveDictionaryDetail, dictionaryDetailDictionaryDetail, addDictionaryDetail } from '../../api/api';

	export default {
		data() {
			return {
				filters: {
                    keyword: ''
				},
				dictionaryDetails: [],
                employees: [],
                options:[],
                table: false,
				total: 0,
				page: 1,
                title:'',
                pageSize: 10,
				listLoading: false,
				sels: [],//列表选中列

				dictionaryDetailFormVisible: false,//编辑界面是否显示
				dictionaryDetailLoading: false,
				dictionaryDetailFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				// 数据字典类型表单数据
				dictionaryDetailForm: {
					id: 0,
                    sn: '',
					name: '',
                    state: 0,
                    manager: null,
                    parent: [],
				},

                dictionaryDetailFormVisible: false,//新增界面是否显示
                dictionaryDetailLoading: false,
                dictionaryDetailFormRules: {// 新增数据校验
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},

			}
		},
		methods: {
			//性别显示转换
			formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},
			handleCurrentChange(val) {
				this.page = val;
				this.getDictionaryDetails();
			},
			//获取数据字典类型列表
			getDictionaryDetails() {
				let para = {
                    keyword: this.filters.keyword,
                    pageSize:this.pageSize,
                    currentPage:this.page
				};
				// console.log(para);
				this.listLoading = true;
				// 向后台发送请求获取值
				this.$http.post("/dicdetail",para)
					.then(result=>{
                        console.log(result);
					   	// 请求成功就从返回参数中取值赋给双向绑定的dictionaryDetails，而值得变动会使页面重新加载渲染
					    this.dictionaryDetails = result.data.list;
                        // console.log(this.dictionaryDetails);
					    this.total = result.data.total;
					    // 关闭页面数据加载特效
                        this.listLoading = false;
					})
					.catch(result=>{
						alert("系统错误！！！");
					})

			},
            //获取员工列表
            getEmployees() {

                // 向后台发送请求获取值
                this.$http.get("/employee")
                    .then(result=>{
                        // console.log(result);
                        // 请求成功就从返回参数中取值赋给双向绑定的employees，而值得变动会使页面重新加载渲染
                        this.employees = result.data;
                        // console.log(this.employees);
                    })
                    .catch(result=>{
                        alert("系统错误！！！");
                    })

            },

			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { id: row.id };
					/*removeDictionaryDetail(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getDictionaryDetails();
					});*/
					this.$http.delete("/dicdetail/"+para.id)
						.then(result=>{
                            if(result.data.success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
							} else {
                                this.$message({
                                    message: '删除失败',
                                    type: 'error'
                                });
							}
                            this.listLoading = false;// 关闭忙等框
							this.page = 1;// 重新定位到第一页
                            this.getDictionaryDetails();// 重新加载数据
						})
	                        .catch(result => { // 失败了也要定位到第一页
                            this.listLoading = false;// 关闭忙等框
                            alert(result.data.message);
                        });
				}).catch(() => {
					alert("系统错误");
				});
			},

			//显示编辑界面
			handleDictionaryDetail: function (index, row) {
                this.title = "编辑"
                this.getTree();
				this.dictionaryDetailFormVisible = true;
				this.dictionaryDetailForm = Object.assign({}, row);// 克隆当前行数据用于回显
                console.log(this.dictionaryDetailForm);
                let dirPath = row.dirPath;
                // console.log(dirPath);//   /1/11/27
                let array = dirPath.split("/");
                // console.log(array);//["", "1", "11", "27"]
                let parent = [];
                // 将字符串数组解析为数字数组，且是回显上级数据字典类型，所以最后一个不要，第一个为空也不要
                for (let i = 1;i < array.length - 1;i++){
					parent.push(parseInt(array[i]));
                }
                // console.log(parent);
                this.dictionaryDetailForm.parent = parent;
			},

			//显示新增界面
            handleAdd: function () {

			    this.title = "添加"
				this.getTree();
				this.dictionaryDetailFormVisible = true;
				this.dictionaryDetailForm = {// 清空模态框的数据
                    id: null,
                    sn: '',
                    name: '',
                    state: '',
                    manager: null,
                    parent: []
				};
			},
			//编辑
			dictionaryDetailSubmit: function () {
                // validate（）方法可以检验整个表单，可以传入两个参数：第一个是是否校验成功和，第二个是未通过校验的字段。只写一个默认是是否校验成功
				this.$refs.dictionaryDetailForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.dictionaryDetailLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.dictionaryDetailForm);
							// console.log(para);
							let arr = para.parent;
                            para.parent  = {"id":arr[arr.length-1]};
							this.$http.put("/dicdetail",para)
                                .then(result=>{
                                    if(result.data.success){
                                        this.$message({
                                            message: '提交成功',
                                            type: 'success'
                                        });
                                    } else {
                                        this.$message({
                                            message: '提交失败',
                                            type: 'error'
                                        });
                                    }
                                    this.dictionaryDetailLoading = false;
                                    this.dictionaryDetailFormVisible = false;
                                    this.getDictionaryDetails();

                                })
                                .catch(result=>{
                                    this.dictionaryDetailLoading = false;
                                })
							/*dictionaryDetailDictionaryDetail(para).then((res) => {
								this.dictionaryDetailLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['dictionaryDetailForm'].resetFields();
								this.dictionaryDetailFormVisible = false;
								this.getDictionaryDetails();
							});*/
						});
					}
				});
			},
			selsChange: function (sels) {// 每选中一行都会把该行的数据添加到sels
				this.sels = sels;
				// console.log(sels);
			},
			//批量删除
			batchRemove: function () {
                // 遍历每行数据取出id聚合为一个id的数组
                var ids = this.sels.map(item => item.id);
                // console.log(ids);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { ids: ids };
					this.$http.patch("/dicdetail/dictionaryDetail",para.ids)
                        .then(result=>{
                            if(result.data.success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                            } else {
                                this.$message({
                                    message: '删除失败',
                                    type: 'error'
                                });
                            }
                            this.listLoading = false;// 关闭忙等框
                            this.page = 1;// 重新定位到第一页
                            this.getDictionaryDetails();// 重新加载数据
                        })
                        .catch(result => { // 失败了也要定位到第一页
                            this.listLoading = false;// 关闭忙等框
                            alert("系统错误");
                        });

					/*batchRemoveDictionaryDetail(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getDictionaryDetails();
					});*/
				}).catch(() => {
                    this.listLoading = false;// 关闭忙等框
                    alert("系统错误");
				});
			},
			getTree(){
                this.$http.get("/dicdetail/tree")
                    .then(result=>{
                        // console.log(result);
                        this.options = result.data;
                    })
                    .catch(result=>{

                    })
			},
			search(){// 解决在除首页外的页面上，高级查询无效的bug，原因是翻页后如果不跳回首页就高级查询，
				// 而后端使用了limit，会从当前页-1再*查询的条数开始查询，如果查询结果没有这么多条那么返回结果为空
			    this.page = 1;
			    this.getDictionaryDetails();
			},
            closeDialog(){
                this.$refs['dictionaryDetailForm'].resetFields();
			},
            closeForm(){
                this.dictionaryDetailFormVisible = false;
                this.$refs['dictionaryDetailForm'].resetFields();

            }

		},
		mounted() {
			this.getDictionaryDetails();
			this.getEmployees();


		}
	}

</script>

<style scoped>

</style>